<template>
  <el-dialog
    class="elDialog"
    @close="closeDialog"
    :title="this.addSubject.id?'编辑学科':'新增学科'"
    :visible="addDialogVisible"
    width="30%"
  >
    <el-form
      ref="addSubject"
      label-width="80px"
      :model="addSubject"
      :rules="rules"
    >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input v-model="addSubject.subjectName" placeholder="请输入学科名称"></el-input>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch active-color="#13ce66"
  inactive-color="#ff4949" v-model="isFront"></el-switch>
      </el-form-item>
    </el-form>
    <div class="btnRight">
    <span slot="footer" >
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
    </div>
  </el-dialog>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'subject-add',
  props: {
    addDialogVisible: {
      type: Boolean
    }
  },
  data () {
    return {
      addSubject: {
        subjectName: '',
        isFrontDisplay: null
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      },
      isFront: false
    }
  },
  methods: {
    resetForm () {
      this.$refs.addSubject.resetFields()
      this.addSubject = {
        subjectName: '',
        isFrontDisplay: null,
        id: ''
      }
      this.isFront = false
    },
    closeDialog () {
      this.resetForm()
      this.$emit('closeDialog')
    },
    processDate (value) {
      const map = {
        false: 0,
        true: 1
      }
      return map[value]
    },
    getDate (value) {
      const map = {
        0: false,
        1: true
      }
      return map[value]
    },
    confirm () {
      this.$refs.addSubject.validate(async (valid) => {
        if (!valid) return
        this.addSubject.isFrontDisplay = this.processDate(this.isFront)
        if (this.addSubject.id) {
          await update(this.addSubject)
        } else {
          await add(this.addSubject)
        }
        this.$message.success(`${this.addSubject.id ? '编辑' : '新增'}成功`)
        this.closeDialog()
      })
    },
    // 编辑
    async editSubject (id) {
      const res = await detail(id)
      this.addSubject = res.data
      this.isFront = this.getDate(this.addSubject.isFrontDisplay)
      console.log(res)
    }
  }

}
</script>
<style lang='scss' scoped>
.btnRight{
  text-align: right;
}
</style>
